package com.xique.door.controller;


import com.github.pagehelper.PageInfo;
import com.xique.common.core.domain.R;
import com.xique.common.core.utils.*;
import com.xique.common.core.utils.poi.ExcelUtil;
import com.xique.common.core.web.controller.BaseController;
import com.xique.common.core.web.domain.AjaxResult;
import com.xique.common.core.web.page.TableDataInfo;
import com.xique.common.log.annotation.Log;
import com.xique.common.log.enums.BusinessType;
import com.xique.common.security.annotation.PreAuthorize;
import com.xique.door.api.model.LoginAppUser;
import com.xique.door.api.request.user.RemoteUserListRequest;
import com.xique.door.bean.domain.*;
import com.xique.door.bean.dto.DoorImportTemplateDTO;
import com.xique.door.bean.request.user.UserAddRequest;
import com.xique.door.bean.request.user.UserEditRequest;
import com.xique.door.bean.request.user.UserSelectRequest;
import com.xique.door.bean.validation.UserValidation;
import com.xique.door.bean.vo.user.UserHouseVo;
import com.xique.door.bean.vo.user.UserListVo;
import com.xique.door.biz.service.IBuildHouseUserBizService;
import com.xique.door.biz.service.IUserBizService;
import com.xique.door.service.IBaseUserService;
import com.xique.door.service.IUserService;
import com.xique.door.service.IVisitorService;
import com.xique.system.api.RemoteSystemUserService;
import com.xique.system.api.dto.OperateDTO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 门禁用户信息Controller
 *
 * @author caogq
 * @date 2021-06-10
 */
@RestController
@RequestMapping("/user")
public class UserController extends BaseController {

    @Autowired
    private IBaseUserService baseUserService;

    @Autowired
    private IUserService userService;

    @Autowired
    private AliossUtil aliossUtil;

    @Autowired
    private IVisitorService visitorService;

    @Autowired
    private UserValidation userValidation;

    @Autowired
    private IUserBizService userBizService;

    @Autowired
    private IBuildHouseUserBizService buildHouseUserBizService;

    @Autowired
    private RemoteSystemUserService remoteSystemUserService;

    /**
     * 查询门禁用户信息列表
     */
    @PreAuthorize(hasPermi = "door:user:list")
    @GetMapping("/conditionList")
    public TableDataInfo conditionList(UserSelectRequest request) {
        startPage();
        request.setParkId(SecurityUtils.getParkId());
        List<UserListVo> list = userBizService.selectConditionUserList(request);
        List<String> userIds = list.stream().filter(e -> StringUtils.isNotEmpty(e.getUpdateUser())).map(e -> e.getUpdateUser()).collect(Collectors.toList());
        if (!userIds.isEmpty()) {
            R<List<OperateDTO>> operateList = remoteSystemUserService.getOperateList(StringUtils.join(userIds, ","));
            List<OperateDTO> data = operateList.getData();
            list.forEach(item -> {
                if (StringUtils.isNotNull(item.getUserType()) && item.getUserType() == 1) {
                    BaseUser baseUser = baseUserService.selectBaseUserById(Long.valueOf(item.getUpdateUser()));
                    if(baseUser!=null) {
                        item.setUpdateUser(baseUser.getUserName());
                    }
                } else {
                    OperateDTO operateDTO = data.stream().filter(e -> String.valueOf(e.getOperateId()).equals(item.getUpdateUser())).findAny().orElse(null);
                    if (operateDTO != null) {
                        item.setUpdateUser(operateDTO.getOperateName());
                    }
                }
            });
        }
        return getDataTable(list);
    }

    /**
     * 导出门禁用户信息列表
     */
    @PreAuthorize(hasPermi = "door:user:export")
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {
        User user = new User();
        user.setParkId(SecurityUtils.getParkId());
        List<User> list = userService.selectUserList(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, list, "user");
    }

    /**
     * 新增保存门禁用户信息
     */
    @PreAuthorize(hasPermi = "door:user:add")
    @Log(title = "门禁用户信息", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    public AjaxResult addSave(@RequestBody UserAddRequest request) {
        request.setParkId(SecurityUtils.getParkId());
        AjaxResult validate = userValidation.addUserValidate(request);
        if (!AjaxResult.isSuccess(validate)) {
            return validate;
        }
        return userBizService.addUser(request);
    }

    /**
     * 新增保存门禁用户信息
     */
    @PreAuthorize(hasPermi = "door:user:edit")
    @Log(title = "门禁用户信息", businessType = BusinessType.INSERT)
    @GetMapping("/detail")
    public AjaxResult detail(@RequestParam("id") Long id) {
        return userBizService.detail(id);
    }


    /**
     * 修改保存门禁用户信息
     */
    @PreAuthorize(hasPermi = "door:user:edit")
    @Log(title = "门禁用户信息", businessType = BusinessType.UPDATE)
    @PutMapping("/edit")
    public AjaxResult editSave(@RequestBody UserEditRequest request) {
        AjaxResult result = userValidation.updateUserValidate(request);
        if (!AjaxResult.isSuccess(result)) {
            return result;
        }
        User user = OrikaUtil.convert(request, User.class);
        user.setUserType(0);
        return userBizService.updateUser(user);
    }


    @PreAuthorize(hasPermi = "door:user:remove")
    @Log(title = "门禁用户信息", businessType = BusinessType.DELETE)
    @DeleteMapping("/remove")
    public AjaxResult remove(String ids) {
        return userBizService.remove(ids);

    }


    @ApiOperation(value = "删除用户人脸图片")
    @DeleteMapping("/deleteFacePic")
    public AjaxResult deleteFacePic(@RequestParam(value = "userId", required = false) String userId, @RequestParam("faceKey") String faceKey) {
        if (StringUtils.isEmpty(faceKey)) {
            return AjaxResult.error("必填项不能为空");
        }

        try {
            faceKey = URLDecoder.decode(faceKey, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            System.out.println(e);
        }
        //1、删除oss上的存储
        String status = aliossUtil.delete(faceKey);

        if (status.equals("error")) {
            return AjaxResult.error("error", "oss删除失败！！！");
        }
        if (StringUtils.isNotEmpty(userId)) {
            //2、清除图片和用户的关联
            try {
                userService.clearUserUrl(userId);
            } catch (Exception e) {
                return AjaxResult.error("error", "图片和用户关系删除失败！！！");
            }
        }

        return AjaxResult.success();
    }


    @PreAuthorize(hasPermi = "door:user:view")
    @GetMapping("/dowmImportTemplate")
    public void importTemplate(HttpServletResponse response) throws IOException {
        List<User> userList = new ArrayList<>();
        //导入模板案例数据
        User user = new User();
//        user.setIdCard("330621199605051234");
        user.setUserName("布莱恩特");
        user.setGender("男");
        user.setPassword("123456");
        user.setPhone("15215924608");
        user.setVisitorType("永久名单");
        user.setAddress("浙江省绍兴市镜湖金滩大厦");
        user.setExTime(new Date());
        user.setVisitorCarType("1");
        user.setPersonType(0);
        user.setStatus("1");
        user.setIdentityType("0");
        user.setDoorBeginDate(DateUtils.getNowDate());
        user.setDoorEndDate(DateUtils.getNowDate());
        user.setElevatorBeginDate(DateUtils.getNowDate());
        user.setElevatorEndDate(DateUtils.getNowDate());
        userList.add(user);
        ExcelUtil<User> util = new ExcelUtil<User>(User.class);
        util.exportExcel(response, userList, "门禁用户数据");
    }

    @PostMapping("/upload")
    public AjaxResult importUserData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<User> util = new ExcelUtil<>(User.class);
        List<User> userList = util.importExcel(file.getInputStream());
        if (CollectionUtils.isEmpty(userList)) {
            return AjaxResult.error("excel数据不能为空");
        }
        String message = userService.importUser(SecurityUtils.getParkId(), userList, updateSupport);
        return AjaxResult.success(message);
    }


    /**
     * 用户状态修改
     */
    @Log(title = "用户状态", businessType = BusinessType.UPDATE)
    @PreAuthorize(hasPermi = "door:user:edit")
    @PostMapping("/changeStatus")
    public AjaxResult changeStatus(User user) {
        user.setUserType(0);
        return userService.updateUser(user);
    }


    /**
     * 查询用户的访客列表
     */
    @PreAuthorize(hasPermi = "door:user:edit")
    @PostMapping("/authVisitor/assignlist/{userId}/{parkId}")
    public TableDataInfo allocatedList(Visitor visitor) {
        startPage();
        List<Visitor> visitors = visitorService.selectVisitorList(visitor);
        return getDataTable(visitors);
    }

    /**
     * 查询未分配访客列表
     */
    @PreAuthorize(hasPermi = "door:user:list")
    @PostMapping("/authVisitor/unAssignlist/{parkId}")
    public TableDataInfo unallocatedList(Visitor visitor) {
        startPage();
        List<Visitor> list = visitorService.selectUnAssignVisitorlist(visitor);
        return getDataTable(list);
    }

    /**
     * 用户访客关系保存
     */
    @PostMapping("/authVisitor/selectAll")
    public AjaxResult selectAuthVisitorAll(Long userId, String visitorIds) {
        return toAjax(visitorService.insertUserVisitor(userId, visitorIds));
    }

    /**
     * 住户已绑定的房屋列表
     */
    @PreAuthorize(hasPermi = "door:user:houseList")
    @Log(title = "住户已绑定的房屋列表", businessType = BusinessType.INSERT)
    @GetMapping("/bind/houseList")
    public AjaxResult bindHouseList(@RequestParam(value = "userId") Long userId) {
        List<UserHouseVo> userHouseVos = buildHouseUserBizService.selectBindHouseList(userId);
        return AjaxResult.success(userHouseVos);
    }

    /**
     * 住户未绑定的房屋列表
     */
    @PreAuthorize(hasPermi = "door:user:houseList")
    @Log(title = "住户未绑定的房屋列表", businessType = BusinessType.INSERT)
    @GetMapping("/unBind/houseList")
    public TableDataInfo unBindHouseList(UserSelectRequest request) {
        startPage();
        request.setParkId(SecurityUtils.getParkId());
        List<BuildHouse> buildHouses = buildHouseUserBizService.selectUnBindHouseList(request);
        List<UserHouseVo> userHouseVos = buildHouseUserBizService.convertUnBindHouseList(buildHouses);
        long total = new PageInfo(buildHouses).getTotal();
        TableDataInfo tableDataInfo = new TableDataInfo(userHouseVos, (int) total);
        return tableDataInfo;
    }

    /**
     * 绑定
     */
    @PreAuthorize(hasPermi = "door:user:houseAdd")
    @Log(title = "绑定", businessType = BusinessType.INSERT)
    @GetMapping("/bindHouse")
    public AjaxResult bindHouse(BuildHouseUser buildHouseUser) {

        return buildHouseUserBizService.bindHouseV2(buildHouseUser);
    }

    /**
     * 解绑
     */
    @PreAuthorize(hasPermi = "door:user:houseCancel")
    @Log(title = "解绑", businessType = BusinessType.DELETE)
    @GetMapping("/unBindHouse")
    public AjaxResult unBindHouse(BuildHouseUser buildHouseUser) {

        return buildHouseUserBizService.unBindHouseV2(buildHouseUser);
    }


    /**
     * ========================================================= adminApi/v1 ===========================================================
     **/

    @PreAuthorize(hasPermi = "door:user:export")
    @GetMapping("/v1/importTemplate")
    public void importTemplateV1(HttpServletResponse response) throws Exception {

        List<DoorImportTemplateDTO> list = userBizService.getDownloadImportTemplateData();

        ExcelUtil<DoorImportTemplateDTO> excel = new ExcelUtil<DoorImportTemplateDTO>(DoorImportTemplateDTO.class);

        excel.exportExcel(response, list, "门禁数据导入模板");
    }

    @PreAuthorize(hasPermi = "door:user:export")
    @PostMapping("/v1/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception {
        ExcelUtil<DoorImportTemplateDTO> util = new ExcelUtil<>(DoorImportTemplateDTO.class);
        List<DoorImportTemplateDTO> list = util.importExcel(file.getInputStream());
        if (CollectionUtils.isEmpty(list)) {
            return AjaxResult.error("excel数据不能为空");
        }
        return userBizService.importData(list, updateSupport);
    }

    @PostMapping("/task/updateInvitationCode")
    public AjaxResult updateInvitationCode() {
        return userBizService.updateInvitationCode();
    }


    /**
     * ========================================================= openApi ===========================================================
     **/

    @PostMapping("/openApi/v1/userList")
    public AjaxResult userListV1(@RequestBody RemoteUserListRequest request) {
        return userBizService.getUserList(request);
    }


    /**
     * ========================================================= miniprogram ===========================================================
     **/
    @GetMapping("/info/{loginName}")
    public R<LoginAppUser> getUserInfo(@PathVariable("loginName") String loginName) {
        return userBizService.getUserInfo(loginName);
    }
}
